import { DataTypes } from 'sequelize'
import sequelize from '../utils/database.js'
import BaseModel from './BaseModel.js'
import { parseTime } from '../utils/helper.js'

class User extends BaseModel {
  static associate(models) {
    // 定义一对一关联
    this.hasOne(models.Sms, { as: 'sms', foreignKey: 'user_id' })

    // 定义一对多关联
    // this.hasMany(models.Sms, { as: 'bb', foreignKey: 'user_id' })
  }
}

User.init({
  id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  created_at: {
    type: DataTypes.DATE,
    get() {
      const rawValue = this.getDataValue('created_at')
      const formattedDate = parseTime(rawValue, '{y}-{m}-{d} {h}:{i}:{s}');
      return formattedDate
    }
  },
  updated_at: {
    type: DataTypes.DATE,
    get() {
      const rawValue = this.getDataValue('created_at')
      const formattedDate = parseTime(rawValue, '{y}-{m}-{d} {h}:{i}:{s}');
      return formattedDate
    }
  },
}, {
  sequelize,
  modelName: 'User',
  tableName: 'user'
})

export default User